<?php
/**
 * Created by PhpStorm.
 * User: s.utkin
 * Date: 28.10.2014
 * Time: 17:46
 */
namespace Messenger\Messages\Send;


use Messenger\Groups;
use Messenger\Messages;
use Messenger\Queue;
use Messenger\Relations;
use Pinenut\Model2\Finder;
use Users\Profile;

class ServiceMessageAction extends \Action{
	/**
	 * Отправляет пользователю сервисное сообщение
	 */
	protected function run()
	{
		$this->response->noRender(true);
		$this->response->noCache(true);

		$serviceType = $this->request->serviceType;
		$targetProfileId = $this->request->targetProfileId;
		$authorProfileId = $this->request->authorProfileId;
		$text = $this->request->text;

		$actionName = $this->request->actionName;
		$actionParams = $this->request->actionParams;

		$serviceTypeProfile = null;

		if ($authorProfileId == null) {
			# Вычисляем id профиля сервисного пользователя
			/** @var Finder $finder */
			$serviceTypeProfile = $finder = Profile::find()->where('serviceType', (int)$serviceType)->one();

			if ($serviceTypeProfile === null) {
				throw new \Exception('Service profile not found', 404);
			}

			$authorProfileId = (string)$serviceTypeProfile;
		}

		$targetProfile = Profile::find($targetProfileId);

		if ($targetProfileId === null || $targetProfile === null) {
			throw new \Exception('Target profile not found', 404);
		}



		$groupModel = Groups::newDialog($targetProfileId, $authorProfileId);
		$groupModel->relations[$targetProfileId]->status = Relations::STATUS_NEUTRAL;
		$isFirstGroupMessage = (int)($groupModel->lastMessageTime == 0);
		$groupModel->unseenMessages[$targetProfileId]->count++;
		$groupModel->addProfileToAuthorsOrderedPool($authorProfileId);
		$groupModel->save();

		# Сохраняем сообщение
		$message = new Messages();
		$message->group[$groupModel];
		$message->text = $text;
		$message->author[$authorProfileId];

		if ($actionName) {
			$action = [
				'name' => $actionName,
				'params' => $actionParams,
			];

			$message->action = $action;
		}

		$message->save();

		$notificationData = [
			'groupId' => (string)$groupModel,
			'messageId' => (string)$message,
			'authorId' => (string)$message->author,
		];

		if ($isFirstGroupMessage) {
			$notificationData['isFirstGroupMessage'] = 1;
		}

		Queue::enqueue(
			[
				'type' => \MessengerNotificationDeliveryConfig::TYPE_NEW_MESSAGE,
				'data' => $notificationData,
			]
		);

		$this->response->content = (string)$message;
	}
}